Skip to content

Conversation

itzexpoexpo
Copy link

@itzexpoexpo itzexpoexpo commented Aug 4, 2025

Currently, clang-format does not allow empty records to be formatted on a single line if the corresponding BraceWrapping.After* option is set to true.

This results in unnecessarily wrapped code:

  struct foo
  {
      int i;
  };

  struct bar
  {};

This patch adds the BraceWrapping.WrapEmptyRecord option, which allows class, struct, and union declarations with empty bodies to be formatted as one-liners, even when After<Record>: true.

As such, the following becomes possible:

  struct foo
  {
      int i;
  };

  struct bar {};

Currently, clang-format does not allow empty records to be formatted
on a single line if the corresponding `BraceWrapping.After*` option
is set to true.

This results in unnecessarily wrapped code:

  struct foo
  {
      int i;
  };

  struct bar
  {
  };

This patch adds the `BraceWrapping.WrapEmptyRecord` option, which
allows `class`, `struct`, and `union` declarations with empty bodies
to be formatted as one-liners, even when `AfterRecord: true`.

As such, the following becomes possible:

  struct foo
  {
      int i;
  };

  struct bar {};
Copy link

github-actions bot commented Aug 4, 2025

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Aug 4, 2025

@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-format

Author: Tomáš Slanina (itzexpoexpo)

Changes

Currently, clang-format does not allow empty records to be formatted on a single line if the corresponding BraceWrapping.After* option is set to true.

This results in unnecessarily wrapped code:

  struct foo
  {
      int i;
  };

  struct bar
  {
  };

This patch adds the BraceWrapping.WrapEmptyRecord option, which allows class, struct, and union declarations with empty bodies to be formatted as one-liners, even when AfterRecord: true.

As such, the following becomes possible:

  struct foo
  {
      int i;
  };

  struct bar {};

Full diff: https://github.com/llvm/llvm-project/pull/151970.diff

5 Files Affected:

  • (modified) clang/include/clang/Format/Format.h (+28)
  • (modified) clang/lib/Format/Format.cpp (+12-1)
  • (modified) clang/lib/Format/TokenAnnotator.cpp (+5-4)
  • (modified) clang/lib/Format/UnwrappedLineParser.cpp (+13-7)
  • (modified) clang/unittests/Format/FormatTest.cpp (+30)
diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h
index 31582a40de866..cc79dcb7b53ec 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1355,6 +1355,32 @@ struct FormatStyle {
     BWACS_Always
   };
 
+  enum BraceWrapEmptyRecordStyle : int8_t {
+    /// Use default wrapping rules for records
+    /// (AfterClass,AfterStruct,AfterUnion)
+    /// \code
+    /// class foo
+    /// {
+    ///   int foo;
+    /// };
+    ///
+    /// class foo
+    /// {
+    /// };
+    /// \endcode
+    BWER_Default,
+    /// Override wrapping for empty records
+    /// \code
+    /// class foo
+    /// {
+    ///   int foo;
+    /// };
+    ///
+    /// class foo {};
+    /// \endcode
+    BWER_Never
+  };
+
   /// Precise control over the wrapping of braces.
   /// \code
   ///   # Should be declared this way:
@@ -1585,6 +1611,8 @@ struct FormatStyle {
     /// \endcode
     ///
     bool SplitEmptyNamespace;
+    /// Wrap empty record (``class``/``struct``/``union``).
+    BraceWrapEmptyRecordStyle WrapEmptyRecord;
   };
 
   /// Control of individual brace wrapping cases.
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 063780721423f..0d72410f00c27 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -200,6 +200,7 @@ template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
     IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
     IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
     IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
+    IO.mapOptional("WrapEmptyRecord", Wrapping.WrapEmptyRecord);
   }
 };
 
@@ -232,6 +233,15 @@ struct ScalarEnumerationTraits<
   }
 };
 
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BraceWrapEmptyRecordStyle> {
+  static void enumeration(IO &IO,
+                          FormatStyle::BraceWrapEmptyRecordStyle &Value) {
+    IO.enumCase(Value, "Default", FormatStyle::BWER_Default);
+    IO.enumCase(Value, "Never", FormatStyle::BWER_Never);
+  }
+};
+
 template <>
 struct ScalarEnumerationTraits<
     FormatStyle::BreakBeforeConceptDeclarationsStyle> {
@@ -1392,7 +1402,8 @@ static void expandPresetsBraceWrapping(FormatStyle &Expanded) {
                             /*IndentBraces=*/false,
                             /*SplitEmptyFunction=*/true,
                             /*SplitEmptyRecord=*/true,
-                            /*SplitEmptyNamespace=*/true};
+                            /*SplitEmptyNamespace=*/true,
+                            /*WrapEmptyRecord=*/FormatStyle::BWER_Default};
   switch (Expanded.BreakBeforeBraces) {
   case FormatStyle::BS_Linux:
     Expanded.BraceWrapping.AfterClass = true;
diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 4801d27b1395a..22132f6d2fd3b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -5935,10 +5935,11 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
 
     // Don't attempt to interpret struct return types as structs.
     if (Right.isNot(TT_FunctionLBrace)) {
-      return (Line.startsWith(tok::kw_class) &&
-              Style.BraceWrapping.AfterClass) ||
-             (Line.startsWith(tok::kw_struct) &&
-              Style.BraceWrapping.AfterStruct);
+      return ((Line.startsWith(tok::kw_class) &&
+               Style.BraceWrapping.AfterClass) ||
+              (Line.startsWith(tok::kw_struct) &&
+               Style.BraceWrapping.AfterStruct)) &&
+             Style.BraceWrapping.WrapEmptyRecord == FormatStyle::BWER_Default;
     }
   }
 
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
index 91b8fdc8a3c38..e3efb0804d988 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -952,20 +952,26 @@ static bool isIIFE(const UnwrappedLine &Line,
 }
 
 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
-                                   const FormatToken &InitialToken) {
+                                   const FormatToken &InitialToken,
+                                   const FormatToken &NextToken) {
   tok::TokenKind Kind = InitialToken.Tok.getKind();
   if (InitialToken.is(TT_NamespaceMacro))
     Kind = tok::kw_namespace;
 
+  bool IsEmptyBlock = NextToken.is(tok::r_brace);
+  bool WrapRecordAllowed =
+      !(IsEmptyBlock &&
+        Style.BraceWrapping.WrapEmptyRecord == FormatStyle::BWER_Never);
+
   switch (Kind) {
   case tok::kw_namespace:
     return Style.BraceWrapping.AfterNamespace;
   case tok::kw_class:
-    return Style.BraceWrapping.AfterClass;
+    return Style.BraceWrapping.AfterClass && WrapRecordAllowed;
   case tok::kw_union:
-    return Style.BraceWrapping.AfterUnion;
+    return Style.BraceWrapping.AfterUnion && WrapRecordAllowed;
   case tok::kw_struct:
-    return Style.BraceWrapping.AfterStruct;
+    return Style.BraceWrapping.AfterStruct && WrapRecordAllowed;
   case tok::kw_enum:
     return Style.BraceWrapping.AfterEnum;
   default:
@@ -3191,7 +3197,7 @@ void UnwrappedLineParser::parseNamespace() {
   if (FormatTok->is(tok::l_brace)) {
     FormatTok->setFinalizedType(TT_NamespaceLBrace);
 
-    if (ShouldBreakBeforeBrace(Style, InitialToken))
+    if (ShouldBreakBeforeBrace(Style, InitialToken, *Tokens->peekNextToken()))
       addUnwrappedLine();
 
     unsigned AddLevels =
@@ -3856,7 +3862,7 @@ bool UnwrappedLineParser::parseEnum() {
   }
 
   if (!Style.AllowShortEnumsOnASingleLine &&
-      ShouldBreakBeforeBrace(Style, InitialToken)) {
+      ShouldBreakBeforeBrace(Style, InitialToken, *Tokens->peekNextToken())) {
     addUnwrappedLine();
   }
   // Parse enum body.
@@ -4151,7 +4157,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr, bool IsJavaRecord) {
     if (ParseAsExpr) {
       parseChildBlock();
     } else {
-      if (ShouldBreakBeforeBrace(Style, InitialToken))
+      if (ShouldBreakBeforeBrace(Style, InitialToken, *Tokens->peekNextToken()))
         addUnwrappedLine();
 
       unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 96cc650f52a5d..3a5233674bd0f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -15615,6 +15615,36 @@ TEST_F(FormatTest, NeverMergeShortRecords) {
                Style);
 }
 
+TEST_F(FormatTest, WrapEmptyRecords) {
+  FormatStyle Style = getLLVMStyle();
+
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterStruct = true;
+  Style.BraceWrapping.AfterClass = true;
+  Style.BraceWrapping.AfterUnion = true;
+  Style.BraceWrapping.SplitEmptyRecord = false;
+
+  verifyFormat("class foo\n{\n  void bar();\n};", Style);
+  verifyFormat("class foo\n{};", Style);
+
+  verifyFormat("struct foo\n{\n  int bar;\n};", Style);
+  verifyFormat("struct foo\n{};", Style);
+
+  verifyFormat("union foo\n{\n  int bar;\n};", Style);
+  verifyFormat("union foo\n{};", Style);
+
+  Style.BraceWrapping.WrapEmptyRecord = FormatStyle::BWER_Never;
+
+  verifyFormat("class foo\n{\n  void bar();\n};", Style);
+  verifyFormat("class foo {};", Style);
+
+  verifyFormat("struct foo\n{\n  int bar;\n};", Style);
+  verifyFormat("struct foo {};", Style);
+
+  verifyFormat("union foo\n{\n  int bar;\n};", Style);
+  verifyFormat("union foo {};", Style);
+}
+
 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
   // Elaborate type variable declarations.
   verifyFormat("struct foo a = {bar};\nint n;");

@llvmbot llvmbot added the clang Clang issues not falling into any other category label Aug 4, 2025
@itzexpoexpo
Copy link
Author

itzexpoexpo commented Aug 5, 2025

Hi! Would @owenca and @mydeveloperday be willing to review this when time permits? Thank you in advance

Copy link

github-actions bot commented Aug 11, 2025

✅ With the latest revision this PR passed the C/C++ code formatter.

@owenca
Copy link
Contributor

owenca commented Aug 14, 2025

See #151590 (comment).

Copy link
Contributor

@HazardyKnusperkeks HazardyKnusperkeks left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add an entry to the changelog. And await feedback from @owenca.

@owenca
Copy link
Contributor

owenca commented Aug 19, 2025

We currently have the following:

BraceWrapping Function Namespace Record (class/struct/union)
After... Yes Yes Yes
SplitEmpty... Yes Yes Yes
AllowShort...OnASingleLine Yes Yes No

So why not add an AllowShortRecordOnASingleLine instead?

@itzexpoexpo
Copy link
Author

My patch targets empty records specifically, an AllowShortRecordOnASingleLine option equivalent to the existing ones would probably format my example as:

  struct foo { int i; };
  struct bar {};

I feel it's functionally closer to the SplitEmpty... options instead.

@owenca
Copy link
Contributor

owenca commented Aug 20, 2025

For the config below

AllowShortFunctionsOnASingleLine: false
BreakBeforeBraces: Custom
BraceWrapping:
  AfterFunction: true
  SplitEmptyFunction: false

You'll get the following format similar to what you want for records:

void f()
{}

So it would make sense to try adding an AllowShortRecordOnASingleLine option for class/struct/union.

@itzexpoexpo
Copy link
Author

I agree that there should be such an option for records too, but my point is that Short != Empty. This does not matter as much for namespaces and functions, but I'd argue that since empty structs are commonly used as tag types, it should be possible to format them on a single line without touching "contentful" structs that just happen to be short elsewhere.

I think both options have their own use-case, and in the end it's a matter of style preference.

@owenca
Copy link
Contributor

owenca commented Aug 20, 2025

Actually, we can use an enum (e.g. Always/All, Empty, Never/None) for AllowShortRecordOnASingleLine similar to AllowShortFunctionsOnASingleLine:

$ cat a.cc
void f()
{
  return;
}

void g() {}
$ cat .clang-format
AllowShortFunctionsOnASingleLine: Empty
BreakBeforeBraces: Custom
BraceWrapping:
  AfterFunction: true
  SplitEmptyFunction: false
$ clang-format a.cc | diff a.cc -
$ 

@itzexpoexpo
Copy link
Author

itzexpoexpo commented Aug 20, 2025

It might be worth notifying me of such a large change before I take the time to polish a solution you were already going to refuse to merge. Should I close and open a new PR since this means starting from the ground-up or will it be okay to just add commits that reverse the existing changes?

@itzexpoexpo
Copy link
Author

Closing in favor of #154580 .

@owenca
Copy link
Contributor

owenca commented Aug 21, 2025

It might be worth notifying me of such a large change before I take the time to polish a solution you were already going to refuse to merge.

How did you know that I was "already going to refuse to merge" when myself didn't because I had not reviewed your patch? Anyway, we have a long-standing high bar for adding new options although it hasn't always been enforced in recent years. Also, it happened from time to time that patches for new options didn't get merged because reviewers (e.g. #118566) or authors themselves (e.g. #150166) had come up with better alternatives.

@itzexpoexpo
Copy link
Author

I deeply apologize for being that harsh on a PR, definitely not fitting here. I felt the 3 weeks of review process were a waste of time but in the end I could reuse a lot of the code in the new PR, so it didn't matter. Completely natural that a better alternative can be found and I agree that this enum AllowShort... solution fits much better into the existing option set.

itzexpoexpo added a commit to itzexpoexpo/llvm-project that referenced this pull request Sep 27, 2025
This commit supersedes PR llvm#151970 by adding the option
AllowShortRecordsOnASingleLine that allows the following formatting:

  struct foo {};
  struct bar { int i; };
  struct baz
  {
    int i;
    int j;
    int k;
  };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang Clang issues not falling into any other category clang-format
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants